package com.huiquan.vocab.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.constant.BaseContants;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.vocab.constant.VocabConstant;
import com.huiquan.vocab.dao.VocabDyadInitDao;
import com.huiquan.vocab.dao.VocabDyadRemoveDao;
import com.huiquan.vocab.domain.VocabDyadRemove;
import com.huiquan.vocab.domain.VocabDyadRemoveSplit;

@Service
public class VocabDyadRemoveService extends BaseService {

	@Autowired
	private VocabDyadRemoveDao vocabDyadRemoveDao;
	@Autowired
	private VocabDyadInitDao vocabDyadInitDao;

	public ModelAndView list(String startStr, String typeKey, String arrayKey, String removeFlagKey,
			String exactSearchFlag,String countPerPageStr) {

		Map<String, Object> param = new HashMap<>();
		if (arrayKey != null && !arrayKey.isEmpty()) {
			if (exactSearchFlag != null && exactSearchFlag.equals("1")) {
				param.put("array", arrayKey);
			} else {
				param.put("array", "%" + arrayKey + "%");
			}
		}
		if (typeKey != null && !typeKey.isEmpty()) {
			param.put("type", typeKey);
		}
		if (removeFlagKey != null && !removeFlagKey.isEmpty()) {
			param.put("removeFlag", removeFlagKey);
		}
		int totalSize = vocabDyadRemoveDao.retrieveSize(param);

		LOGGER.info("List total size=" + totalSize);

		Map<String, Integer> pageNo ;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr, countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr);
		}
		int endPage = pageNo.get("endPage");
		int start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<VocabDyadRemove> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			if (removeFlagKey.equals(BaseContants.FLAG_NULL.toString())) {
				param.put("orderStr", "array");
			} else {
				param.put("orderStr", "gmt_modified desc,array");
			}
			list = vocabDyadRemoveDao.retrieveList(param);
		}

		// 如果是o+oa或者o+s类型的数据，需要有分拆列表
		boolean splitFlag = VocabConstant.DYAD_O_O.equals(typeKey) || VocabConstant.DYAD_O_S.equals(typeKey);
		if (splitFlag) {
			// 将分词和结果词按顺序进行比对，匹配上的词表示不删除
			String[] arrays, patterns, resultArrays, resultPatterns;
			int resultIndex;
			for (VocabDyadRemove dyadRemove : list) {
				List<VocabDyadRemoveSplit> splitList = new ArrayList<VocabDyadRemoveSplit>();

				arrays = dyadRemove.getArray().substring(1).split(",");
				patterns = dyadRemove.getPartPattern().substring(1).split(",");
				resultArrays = dyadRemove.getResultArray().substring(1).split(",");
				resultPatterns = dyadRemove.getResultPattern().substring(1).split(",");

				resultIndex = 0;
				for (int i = 0; i < arrays.length; i++) {
					VocabDyadRemoveSplit split = new VocabDyadRemoveSplit();
					if (resultArrays.length > resultIndex && arrays[i].equals(resultArrays[resultIndex])) {
						split.setFlag(BaseContants.FLAG_NO);
						split.setVocabulary(arrays[i]);
						split.setProperty(resultPatterns[resultIndex]);

						resultIndex++;
					} else {
						split.setFlag(BaseContants.FLAG_YES);
						split.setVocabulary(arrays[i]);
						split.setProperty(patterns[i]);
					}
					splitList.add(split);
				}

				dyadRemove.setSplitList(splitList);
			}
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("arrayKey", "分词");

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, null);
		map.put("showSearch", showSearch);

		return new ModelAndView("vocab/dyad_index", map);
	}

	/**
	 * 添加未校验的remove数据
	 * 
	 * @param array
	 * @param partPattern
	 * @return
	 */
	public ReturnData add(String array, String partPattern, String type) throws Exception {
		// 判断是否已存在
		Map<String, Object> param = new HashMap<>();
		param.put("type", type);
		param.put("array", array);
		param.put("partPattern", partPattern);
		VocabDyadRemove existRemove = vocabDyadRemoveDao.retrieveObjectByMap(param);

		if (existRemove == null) {
			existRemove = new VocabDyadRemove();
			existRemove.setType(type);
			existRemove.setArray(array);
			existRemove.setPartPattern(partPattern);
			existRemove.setResultArray(array);
			existRemove.setResultPattern(partPattern);
			existRemove.setRemoveFlag(BaseContants.FLAG_NO);

			Long removeId = vocabDyadRemoveDao.insert(existRemove);

			vocabDyadInitDao.initRemoveStd(removeId);

		} else {
			ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
			rc.setDesc("添加的该remove分词已存在！");
			return ReturnUtil.fail(rc);
		}

		return ReturnUtil.success();
	}

	/**
	 * remove页面校验后提交，根据类型进行不同处理：如果是o+oa或o+s类型则需要更改结果词，其他类型只需要修改remove标志（
	 * 结果词之前已维护好，页面上只有标志位的判断）
	 * 
	 * @param type
	 * @param ids
	 * @param flags
	 * @param replaceVocabs
	 * @param replaceProps
	 * @param user
	 * @return
	 */
	public ReturnData checkPage(String type, String[] ids, String[] flags, String[] resultArrays,
			String[] resultPatterns, User user) throws Exception {

		for (int i = 0; i < ids.length; i++) {
			Long id = Long.parseLong(ids[i]);

			VocabDyadRemove remove = new VocabDyadRemove();
			remove.setId(id);
			remove.setRemoveFlag(Integer.parseInt(flags[i]));
			if (type.equals("o+oa") || type.equals("o+s")) {
				remove.setResultArray(resultArrays[i]);
				remove.setResultPattern(resultPatterns[i]);
			}
			vocabDyadRemoveDao.update(remove);
			vocabDyadInitDao.initRemoveStd(id);
		}

		return ReturnUtil.success();
	}

}
